package com.mdd.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.common.base.page.PageValidate;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.Region;
import com.mdd.common.mapper.RegionMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.validate.StatusValidate;
import com.mdd.store.entity.Store;
import com.mdd.store.mapper.StoreMapper;
import com.mdd.store.service.IStoreService;
import com.mdd.store.validate.StoreCreateValidate;
import com.mdd.store.validate.StoreSearchValidate;
import com.mdd.store.validate.StoreUpdateValidate;
import com.mdd.store.vo.StoreDetailVo;
import com.mdd.store.vo.StoreListedVo;
import com.mdd.system.api.SystemAuthAdminApi;
import com.mdd.system.params.SystemAdminParams;
import com.mdd.system.vo.RegionDetailVo;
import com.mdd.system.vo.SystemAuthAdminInformVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 门店（店铺）实现类
 * @author LikeAdmin
 */
@Service
@Transactional
public class StoreServiceImpl extends ServiceImpl<StoreMapper,Store> implements IStoreService {

    @Resource
    StoreMapper storeMapper;
    @Resource
    RegionMapper regionMapper;
    @Resource
    SystemAuthAdminApi systemAuthAdminApi;

    /**
     * 门店（店铺）列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<PmsStoreListedVo>
     */
    @Override
    public PageResult<StoreListedVo> list(PageValidate pageValidate, StoreSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        if(searchValidate.getStatus() != null) {
            queryWrapper.eq(Store::getStatus, searchValidate.getStatus());
        }
        if(searchValidate.getTradeFlag() != null) {
            queryWrapper.eq(Store::getStatus, searchValidate.getTradeFlag());
        }
        if(StringUtils.isNotEmpty(searchValidate.getName())) {
            queryWrapper.eq(Store::getName, searchValidate.getName());
        }
        if(StringUtils.isNotEmpty(searchValidate.getPhone())) {
            queryWrapper.eq(Store::getPhone, searchValidate.getPhone());
        }
        SystemAuthAdminInformVo systemAuthAdmin = systemAuthAdminApi.getCurrentUser();
        if (!systemAuthAdmin.getDeptIds().equals(1L)) {
            queryWrapper.likeRight(Store::getDeptCode, systemAuthAdmin.getDeptCode());
        }
        queryWrapper.orderByDesc(Store::getId);


        IPage<Store> iPage = storeMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<StoreListedVo> list = new LinkedList<>();
        for(Store item : iPage.getRecords()) {
            StoreListedVo vo = new StoreListedVo();
            BeanUtils.copyProperties(item, vo);
            //todo 后续地区加入至缓存 从缓存中读取
            Region province =regionMapper.selectById(item.getProvince());
            Region city =regionMapper.selectById(item.getCity());
            Region country =regionMapper.selectById(item.getCounty());
            RegionDetailVo provinceVo  =new RegionDetailVo();
            RegionDetailVo cityVo  =new RegionDetailVo();
            RegionDetailVo countryVo  =new RegionDetailVo();

            BeanUtils.copyProperties(province, provinceVo);
            BeanUtils.copyProperties(city, cityVo);
            BeanUtils.copyProperties(country, countryVo);
            vo.setProvince(provinceVo);
            vo.setCity(cityVo);
            vo.setCounty(countryVo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public List<StoreListedVo> selectList() {
        LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
        SystemAuthAdminInformVo systemAuthAdmin = systemAuthAdminApi.getCurrentUser();
        if (!systemAuthAdmin.getDeptIds().equals(1L)) {
            queryWrapper.likeRight(Store::getDeptCode, systemAuthAdmin.getDeptCode());
        }
        queryWrapper.orderByDesc(Store::getId);


        List<Store> stores = storeMapper.selectList(queryWrapper);

        List<StoreListedVo> list = new LinkedList<>();
        for(Store item : stores) {
            StoreListedVo vo = new StoreListedVo();
            BeanUtils.copyProperties(item, vo);
            //todo 后续地区加入至缓存 从缓存中读取
            Region province =regionMapper.selectById(item.getProvince());
            Region city =regionMapper.selectById(item.getCity());
            Region country =regionMapper.selectById(item.getCounty());
            RegionDetailVo provinceVo  =new RegionDetailVo();
            RegionDetailVo cityVo  =new RegionDetailVo();
            RegionDetailVo countryVo  =new RegionDetailVo();

            BeanUtils.copyProperties(province, provinceVo);
            BeanUtils.copyProperties(city, cityVo);
            BeanUtils.copyProperties(country, countryVo);
            vo.setProvince(provinceVo);
            vo.setCity(cityVo);
            vo.setCounty(countryVo);
            list.add(vo);
        }
        return list;
    }

    /**
     * 门店（店铺）详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return PmsStore
     */
    @Override
    public StoreDetailVo detail(Long id) {
        Store model = storeMapper.selectById(id);

        Assert.notNull(model, "门店数据不存在");

        StoreDetailVo vo = new StoreDetailVo();
        BeanUtils.copyProperties(model, vo);
        Region province =regionMapper.selectById(model.getProvince());
        Region city =regionMapper.selectById(model.getCity());
        Region country =regionMapper.selectById(model.getCounty());
        RegionDetailVo provinceVo  =new RegionDetailVo();
        RegionDetailVo cityVo  =new RegionDetailVo();
        RegionDetailVo countryVo  =new RegionDetailVo();

        BeanUtils.copyProperties(province, provinceVo);
        BeanUtils.copyProperties(city, cityVo);
        BeanUtils.copyProperties(country, countryVo);
        vo.setProvince(provinceVo);
        vo.setCity(cityVo);
        vo.setCounty(countryVo);
        return vo;
    }

    /**
     * 门店（店铺）新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Transactional
    @Override
    public void add(StoreCreateValidate createValidate) {
        SystemAuthAdminInformVo adminInformVo = systemAuthAdminApi.findByUsername(createValidate.getAdminUsername());
        Assert.isNull(adminInformVo, "门店管理员账号已存在！");
        Store store = storeMapper.selectOne(new QueryWrapper<Store>()
                .eq("name",createValidate.getName())
                .last("limit 1"));
        Assert.isNull(store, "该门店已存在！");
        Store model = new Store();
        model.setStoreCode(createValidate.getStoreCode());
        model.setName(createValidate.getName());
        model.setBImgUrl(createValidate.getBImgUrl());
        model.setLImgUrl(createValidate.getLImgUrl());
        model.setGuideImgUrl(createValidate.getGuideImgUrl());
        model.setStatus(createValidate.getStatus());
        model.setLon(createValidate.getLon());
        model.setLng(createValidate.getLng());
        model.setLabel(createValidate.getLabel());
        model.setType(createValidate.getType());
        model.setPhone(createValidate.getPhone());
        model.setOpenTime(createValidate.getOpenTime());
        model.setCloseTime(createValidate.getCloseTime());
        model.setProvince(createValidate.getProvince());
        model.setCity(createValidate.getCity());
        model.setCounty(createValidate.getCounty());
        model.setContent(createValidate.getContent());
        model.setAddress(createValidate.getAddress());
        model.setDescription(createValidate.getDescription());
        model.setRetailPrice(createValidate.getRetailPrice());
        model.setCurrentPrice(createValidate.getCurrentPrice());
        model.setSalesVolume(0);
        model.setScore(createValidate.getScore());
        model.setAveragePrice(createValidate.getAveragePrice());
        model.setAdminUsername(createValidate.getAdminUsername());
        //门店所属部门 目前设置为创建账号
        model.setDeptCode(adminInformVo.getDeptCode());
        model.setMerchantId(adminInformVo.getDeptIds());
        storeMapper.insert(model);
        SystemAdminParams systemAdminParams=new SystemAdminParams();
        //创建账号
        systemAdminParams.setUsername(createValidate.getAdminUsername());
        systemAdminParams.setNickname(createValidate.getName()+"管理员");
        systemAdminParams.setPassword(createValidate.getAdminPassword());
        //设置部门 门店所属部门设置为上级cp部门
        systemAdminParams.setDeptIds(adminInformVo.getDeptIds());
        systemAdminParams.setStoreId(model.getId());
        //todo 设置默认岗位
        systemAdminParams.setPostIds(0L);
        //todo 设置默认角色
        systemAdminParams.setRoleIds(3L);
        systemAuthAdminApi.addAdminInfo(systemAdminParams,model.getId());
    }
    @Transactional
    @Override
    public void updateStatus(StatusValidate statusValidate) {
        Store model = storeMapper.selectOne(
                new QueryWrapper<Store>()
                        .eq("id", statusValidate.getId())
                        .last("limit 1"));

        Assert.notNull(model, "门店数据不存在!");
        model.setStatus(statusValidate.getStatus());
        storeMapper.updateById(model);
    }

        /**
         * 门店（店铺）编辑
         *
         * @author LikeAdmin
         * @param updateValidate 参数
         */
        @Transactional
    @Override
    public void edit(StoreUpdateValidate updateValidate) {
        Store model = storeMapper.selectOne(
                new QueryWrapper<Store>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

            Assert.notNull(model, "门店数据不存在!");

        model.setId(updateValidate.getId());
        model.setStoreCode(updateValidate.getStoreCode());
        model.setName(updateValidate.getName());
        model.setBImgUrl(updateValidate.getBImgUrl());
        model.setLImgUrl(updateValidate.getLImgUrl());
        model.setGuideImgUrl(updateValidate.getGuideImgUrl());
        model.setStatus(updateValidate.getStatus());
        model.setLon(updateValidate.getLon());
        model.setLng(updateValidate.getLng());
        model.setLabel(updateValidate.getLabel());
        model.setType(updateValidate.getType());
        model.setPhone(updateValidate.getPhone());
        model.setOpenTime(updateValidate.getOpenTime());
        model.setCloseTime(updateValidate.getCloseTime());
        model.setProvince(updateValidate.getProvince());
        model.setCity(updateValidate.getCity());
        model.setCounty(updateValidate.getCounty());
        model.setContent(updateValidate.getContent());
        model.setScore(updateValidate.getScore());
        model.setAddress(updateValidate.getAddress());
        model.setDescription(updateValidate.getDescription());
        model.setRetailPrice(updateValidate.getRetailPrice());
        model.setCurrentPrice(updateValidate.getCurrentPrice());
        model.setAveragePrice(updateValidate.getAveragePrice());
        storeMapper.updateById(model);
    }

    /**
     * 门店（店铺）删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Transactional
    @Override
    public void del(Long id) {

        Store model = storeMapper.selectOne(
                new QueryWrapper<Store>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "门店数据不存在!");
        storeMapper.deleteById(model);
    }

    @Override
    public List<StoreListedVo> listAllByDeptCode( ) {
        SystemAuthAdminInformVo adminInformVo = systemAuthAdminApi.getCurrentUser();
        String deptCode = adminInformVo.getDeptCode();
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("dept_code",deptCode);
        queryWrapper.orderByDesc("id");
        List<Store> pmsStoreList = storeMapper.selectList(queryWrapper);
        List<StoreListedVo> pmsStoreListedVoList = new ArrayList<>(pmsStoreList.size());
        pmsStoreList.forEach(pmsStore -> {
            StoreListedVo pmsStoreListedVo = new StoreListedVo();

            BeanUtils.copyProperties(pmsStore,pmsStoreListedVo);
            Region province =regionMapper.selectById(pmsStore.getProvince());
            Region city =regionMapper.selectById(pmsStore.getCity());
            Region country =regionMapper.selectById(pmsStore.getCounty());
            RegionDetailVo provinceVo  =new RegionDetailVo();
            RegionDetailVo cityVo  =new RegionDetailVo();
            RegionDetailVo countryVo  =new RegionDetailVo();

            BeanUtils.copyProperties(province, provinceVo);
            BeanUtils.copyProperties(city, cityVo);
            BeanUtils.copyProperties(country, countryVo);
            pmsStoreListedVo.setProvince(provinceVo);
            pmsStoreListedVo.setCity(cityVo);
            pmsStoreListedVo.setCounty(countryVo);
            pmsStoreListedVoList.add(pmsStoreListedVo);
        });
        return pmsStoreListedVoList;
    }

}
